//
//  BaseCollectionView.m
//  BaseCode
//
//  Created by 曹连华 on 2020/3/25.
//

#import "BaseCollectionView.h"
#import "BaseCollectionViewCell.h"
#import "BaseCollectionReusableView.h"
#import <ReactiveObjC/RACSignal.h>
#import <ReactiveObjC/NSObject+RACDeallocating.h>
#import <ReactiveObjC/RACEXTScope.h>

@implementation BaseCollectionView

- (id)dequeueReusableCellWithReuseIdentifier:(NSString *)identifier forIndexPath:(NSIndexPath *)indexPath {
    UICollectionViewCell *cell = [super dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
    
    if ([cell isKindOfClass:[BaseCollectionViewCell class]]) {
        [(BaseCollectionViewCell *)cell setIndexPath:indexPath];
    }
    
    return cell;
}

- (id)dequeueReusableSupplementaryViewOfKind:(NSString *)elementKind withReuseIdentifier:(NSString *)identifier forIndexPath:(NSIndexPath *)indexPath {
    UICollectionViewCell *cell = [super dequeueReusableSupplementaryViewOfKind:elementKind withReuseIdentifier:identifier forIndexPath:indexPath];
    
    if ([cell isKindOfClass:[BaseCollectionReusableView class]]) {
        [(BaseCollectionReusableView *)cell setIndexPath:indexPath];
    }
    
    return cell;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)setDelegate:(id<UICollectionViewDelegate>)delegate {
    [super setDelegate:delegate];
    
    if (delegate == nil) {
        return;
    }
    @weakify(self);
    [((NSObject*)delegate).rac_willDeallocSignal subscribeCompleted:^{
        @strongify(self);
        self.delegate = nil;
        self.dataSource = nil;
    }];
}

- (void)reloadData {
    [self.collectionViewLayout invalidateLayout];
    [super reloadData];
}

@end
